package com.lanou.userLogin.cart.web.servlet;

import com.lanou.userLogin.cart.domin.CartItem;
import com.lanou.userLogin.cart.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/cartAddServlet")
public class CartAddServlet extends HttpServlet {

    private CartService cs = new CartService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String bid = req.getParameter("bid");
        int count = Integer.parseInt(req.getParameter("count"));
        List<CartItem> cl = (List<CartItem>) session.getAttribute("cartItemList");
        List<CartItem> cil = cs.cartAdd(bid, cl, count);
        double sumMoney = 0;
        for (CartItem cartItem : cil) {
            sumMoney = sumMoney + cartItem.getBook().getPrice() * cartItem.getCount();
//            BigDecimal b = new BigDecimal(sumMoney);
//            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//            req.setAttribute("sumMoney",f1);
        }
        session.setAttribute("sumMoney", sumMoney);
        req.getSession().setAttribute("cartList", cil);
        req.getRequestDispatcher("/jsps/cart/list.jsp").forward(req, resp);
    }
}



